﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using ET;
using Marx;
using Server;

namespace Demo
{
	public class GateInfo
	{
		public int Id;
		public string OuterAddress;
		public long Token;
	}

	[ObjectSystem]
	public class GateSelectorAwakeSystem : AwakeSystem<GateSelectorComponent>
	{
		public override void Awake(GateSelectorComponent self)
		{
			self.Awake();
		}
	}

	public class GateSelectorComponent : Entity, IAwake
	{
		public readonly List<StartSceneConfig> GateScenes = new List<StartSceneConfig>();
		public readonly Dictionary<int, StartSceneConfig> Id_GateScene = new Dictionary<int, StartSceneConfig>();

		public void Awake()
		{
			int zone = this.DomainZone();
			GateScenes.AddRange(StartConfig.Instance.Scenes.Where(i => i.Type == MarxSceneType.Gate && i.ZoneId == zone));

			foreach (var config in GateScenes)
			{
				Id_GateScene.Add(config.ID, config);
			}
		}

		public async ETTask<GateInfo> Get(Account account)
		{
			try
			{
				var sender = await ServiceManager.Instance.GetServiceSender(this.DomainZone(), ServiceName.PlayerService);
				SSGetClientLocationResponse resp = await sender.Call(new SSGetClientLocationRequest() { AccountId = account.Id }) as SSGetClientLocationResponse;
				var config = Id_GateScene[resp.GateAppId];

				// 向gate请求一个key,客户端可以拿着这个key连接gate
				var tokenReq = new SSRegLoginTokenRequest()
				{
					Account = account.Name,
					AccountId = account.Id,
					GateAppId = resp.GateAppId,
					LogicAppId = resp.LogicAppId,
				};
				tokenReq.Players.AddRange(account.Players);
				SSRegLoginTokenResponse tokenResp = await MessageHelper.CallActor(config.InstanceId, tokenReq) as SSRegLoginTokenResponse;

				string outerAddress = config.OuterEndPoint.ToString();
				return new GateInfo() { Id = config.ID,  OuterAddress = outerAddress, Token = tokenResp.Token };
			}
			catch (Exception e)
			{
				Log.Error(e);
				Log.Error("Find gate address failed.");
				return null;
			}
		}
	}

}
